package LeedCode_BinaryTree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:二叉树的分层遍历
 * User: 阿宾
 * Date: 2024-11-26
 * Time: 19:33
 */
public class Demo7 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }
    public List<List<Integer>> levelOrder(TreeNode root){
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null){
            return ret;
        }
        //创建队列
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            //创建临时队列
            List<Integer> tmp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                //出队
                TreeNode cur = queue.poll();
                tmp.add(cur.val);
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }
}
